package com.yand.thinkingInJava.thinkingInJava21.join;

/**
 * interrupt() 方法，中断线程的状态，由 false 改为true;
 * 如果程序中有出现阻塞线程的方法如 ：sleep  wait 则 抛出异常中断线程执行
 * isInterrupted() 方法 获取线程是否中断
 *
 *
 */
class Sleeper extends Thread{
    private int duration;
    public Sleeper(String name, int sleepTime){
        super(name);
        duration = sleepTime;
        start();
    }

    public void run(){
        try{
            sleep(duration);
        }catch (InterruptedException e){
            System.out.println(getName() +" was Interrupted."+"isInterrupted():"+isInterrupted());
            return;
        }

      //  System.out.println(getName() +" has awakened");
    }
}

class Joiner extends Thread{
      private Sleeper sleeper;
      public Joiner(String name, Sleeper sleeper){
          super(name);
          this.sleeper = sleeper;
          start();
      }

      public void run(){
          try{
              sleeper.join();
          }catch (InterruptedException e){
              System.out.println("Interrupted");
          }
          System.out.println(getName() + " join completed");
      }
}







/**
 * 加入一个线程，当前线程被挂起， 等 join进来的那个线程先跑完，之后，再跑。
 */
public class Joining {

    public static void main(String [] args) throws InterruptedException {

        Sleeper sleeper = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);
        Joiner dopey = new Joiner("Dopey",sleeper);
        Joiner doc = new Joiner("Doc",grumpy);


        grumpy.interrupt();

    }
}
